#include "guiterm.hpp"
#include <QDesktopServices>
#include <QUrl>

string cygpathToAbsolute(string filename)
{
	QProcess cygpathProcess;
	QStringList args;
		args.append("-w");
		args.append(filename.c_str());
	cygpathProcess.start("cygpath", args);
	cygpathProcess.waitForFinished();
	QByteArray out = cygpathProcess.readAllStandardOutput();
	
	string ret = out.data();
	
	// Replace backslashes with forward slashes
	for(int ii=0; ii<ret.length(); ii++)
		if(ret[ii] == '\\') ret[ii] = '/';
	// Strip trailing newline
	if(ret.length() && ret[ret.length()-1]=='\n')
		ret = ret.substr(0, ret.length()-1);
	
	return ret;
}

FileLocalView::FileLocalView(RemoteJob *owner, ServerConnection *host, const RPCParams *params)
	:JobViewSegment(owner)
{
	this->filename = params->getString("file");
	
	setLayout(new QVBoxLayout());
		layout()->setContentsMargins(0,0,0,0);
	frame = new WidgetFrame(this);
	layout()->addWidget(frame);
	
	if(host->isLocal())
	{
		this->localName = filename;
#ifdef __MINGW32__
		localName = cygpathToAbsolute(localName);
#endif
		viewFile(localName);
	}
	else
	{
		frameLayout = new QVBoxLayout();
			frameLayout->setSpacing(0);
		frame->setLayout(frameLayout);
		
		downloadProgressLine = new QHBoxLayout();
			downloadProgressLine->setSpacing(0);
			downloadProgressLine->setContentsMargins(0,0,0,0);
		downloadLabel = new QLabel(filename.c_str());
			downloadProgressLine->addWidget(downloadLabel);
		downloadProgressBar = new QProgressBar();
			downloadProgressLine->addWidget(downloadProgressBar);
			downloadProgressBar->setMaximum(FILETRANSFER_PROGRESS_MAX);
		frameLayout->addLayout(downloadProgressLine);
		
		string basename = Path(filename.c_str()).basename();
		this->localName = TempFileManager::instance()->getTempFile(basename);
		
		FileTransfer *download = new FileTransfer(host, filename);
		connect(download, SIGNAL(updateProgress(string,double)), this, SLOT(updateProgress(string,double)));
		connect(download, SIGNAL(fileFinished(string,string)), this, SLOT(downloadFinished(string,string)));
		connect(download, SIGNAL(fileFailed(string,string)), this, SLOT(downloadFailed(string,string)));
		download->begin(this->localName);
	}
}

FileLocalView::~FileLocalView()
{
	delete frame;
}

void FileLocalView::updateProgress(string filename, double progress)
{
	downloadProgressBar->setValue(int(progress * FILETRANSFER_PROGRESS_MAX));
}

void FileLocalView::downloadFinished(string remoteFilename, string localFilename)
{
	viewFile(localFilename);
}

void FileLocalView::downloadFailed(string filename, string message)
{
	job->reportError(message);
}

void FileLocalView::viewFile(string localName)
{
#ifdef __MINGW32__
	string url = "file:///"+localName;
#else
	string url = "file://"+localName;
#endif
	
	if(!QDesktopServices::openUrl(QUrl(url.c_str(), QUrl::TolerantMode))) {
		job->reportError(retprintf("Failed to open %s\n", url.c_str()));
	}
}

RPC_HANDLER(localview)
{
	RemoteJob *job = getJob(host, params);
	JobView *view = job->getView();
	view->addSegment(new FileLocalView(job, (ServerConnection*)host, params));
}

